import { getMemberDetail, getMemberList, downLoadFile } from './allBrokerDetailServ.js'
import { parse } from 'qs'
import { message } from 'antd'
import moment from 'moment'
import { isEmpty, isArray, cloneDeep, merge } from 'lodash'
import { hashHistory } from 'dva/router'
import { download } from 'utils/util'

const defultState = {
  loading: false,
  btnLoading: false,
  listData: {},
  tableData: {dataSource: []},
  exportLoading: false,
  detailData: {},//详情数据
  id: '',//id
  activeKey: '',//选中的tabs
  url: ''
}

// 声明module
const tmpModule = {
  state: cloneDeep(defultState),
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({pathname, query}) => {
        
        if ('' + tmpModule.pathname === '' + pathname) {
          dispatch({type: 'updateStore', payload: {id: query.id}})
          dispatch({type: 'queryInfo', payload: {}}) // end dispatch
        }
      })
    },
  },
  
  // 方法列表
  effects: {
    // 查询记录
    * queryInfo ({payload}, {put, call, select}) {
      try {
        let {id, tableData, listData} = yield select(state => state[tmpModule.namespace])
        const {data, success} = yield call(getMemberDetail, parse({id: id}))
        
        if (success) {
          yield put({type: 'updateStore', payload: {detailData: data}})
          let result = yield call(getMemberList, parse({
            accountId: id,
            pageNo: payload.pageNo || 1,
            pageSize: payload.pageSize || 10
          }))
          
          if (result.success) {
            
            tableData.dataSource = result.rows
            listData = result
            
            yield put({type: 'updateStore', payload: {tableData, listData}})
          }
        }
      } catch (e) {
        console.error(e)
      }
    },
    * downLoad ({payload}, {put, call, select}) {
      try {
        yield put({type: 'updateStore', payload: {exportLoading: true}})
        const {data, success, msg} = yield call(downLoadFile, parse(payload))
        yield put({type: 'updateStore', payload: {exportLoading: false}})
        if (success) {
          let url = data || ''
          if (url) {
            download(url)
          }
          yield put({type: 'updateStore', payload: {url: data}})
        } else {
          message.error(`${msg}`)
        }
      } catch (e) {
        console.error(e)
      }
    },
  },
  
  reducers: {
    updateStore (preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
